package com.lili.comnonbase.exception;

import com.lili.utilscommon.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * /**
 * 统一异常处理类
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 这是粗略的异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result error(Exception e) {
        e.printStackTrace();
        log.error(e.getMessage());
        return Result.error();
    }

    /**
     * 这里是算数异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody
    public Result handleArithmeticExcpetion(ArithmeticException e) {
        e.printStackTrace();
        log.error(e.getMessage());
        return Result.error().message("算数异常");
    }

    /**
     * 这里是空指针异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public Result handleNullPointerException(NullPointerException e) {
        e.printStackTrace();
        log.error(e.getMessage());
        return Result.error().message("空指针异常");
    }

    /**
     * 这里是数组越界异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(ArrayIndexOutOfBoundsException.class)
    @ResponseBody
    public Result handArrayIndexOutOfBoundsException(ArrayIndexOutOfBoundsException e) {
        e.printStackTrace();
        log.error(e.getMessage());
        return Result.error().message("数组越界异常");
    }

    /**
     * 通过Id查询一个用户 user是空的 业务异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public Result error(BusinessException e) {
        e.printStackTrace();
        log.error(e.getMessage());
        return Result.error().message(e.getMsg()).code(e.getCode());
    }
}
